package com.psy.counseling.utils;

import com.psy.counseling.entity.User;
import lombok.Data;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;

/**
 * ClassName:ImportDataUtil
 * Package:com.cxh.easyexcel
 * Description:
 *
 * @Date:2022/6/3 16:58
 * @Author:cxh
 */
@Data
public class ImportDataUtil {
    private ArrayList<User> importSuccess;
    private ArrayList<Integer> importError;

    public ImportDataUtil(FileInputStream inputStream) throws IOException {
        importError = new ArrayList<>();
        importSuccess = new ArrayList<>();
        ImportData(inputStream);
    }

    public void ImportData(FileInputStream inputStream) throws IOException {
        XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
        XSSFSheet sheet = workbook.getSheetAt(0);
        int lastRowNum = sheet.getLastRowNum();
        for (int i = 1; i <= lastRowNum; i++) {
            XSSFRow row = sheet.getRow(i);
            DecimalFormat df = new DecimalFormat("#");
            XSSFCell userNameCell = row.getCell(0);
            XSSFCell emailCell = row.getCell(1);
            XSSFCell realNameCell = row.getCell(2);
            XSSFCell sexCell = row.getCell(3);
            XSSFCell ageCell = row.getCell(4);
            XSSFCell facultyCell = row.getCell(5);
            XSSFCell telephoneCell = row.getCell(6);
            if (userNameCell==null || emailCell.getCellType()== CellType.BLANK || realNameCell==null || sexCell == null
                    || ageCell == null || facultyCell == null || telephoneCell == null) {
                importError.add(i+1);
                continue;
            }
            User user = new User();
            double str = Double.parseDouble(userNameCell.toString());
            String userName = df.format(str);
            user.setUsername(userName);
            user.setEmail(emailCell.getStringCellValue());
            user.setRealName(realNameCell.getStringCellValue());
            user.setSex(sexCell.getStringCellValue());
            String age = df.format(Double.parseDouble(ageCell.toString()));
            user.setAge(age);
            user.setFaculty(facultyCell.getStringCellValue());
            String telephone = df.format(Double.parseDouble(telephoneCell.toString()));
            user.setTelephone(telephone);
            importSuccess.add(user);
        }
    }

}
